package top.kaoshanji.p1ch03b;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.StandardCharsets;

/**
 * 代码清单-p1ch03b-03：为客户端返回令牌
 * @author kaoshanji
 * ^_^
 * create time 2025/5/25 14:13
 */
@WebServlet(urlPatterns = {"/token"})
public class TokenServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 设置请求对象的编码
        req.setCharacterEncoding(StandardCharsets.UTF_8.name());

        String clientId = req.getParameter("client_id");
        String clientSecret = req.getParameter("client_secret");
        String code = req.getParameter("code");

        System.out.println("...为客户端颁发令牌...clientId:"+clientId+",clientSecret="+clientSecret+",code="+code);

        String token = "token-" + System.nanoTime();
        System.out.println("...授权服务器生成令牌..."+token);

        // 设置响应对象的编码
        resp.setContentType(StandardCharsets.UTF_8.name());
        PrintWriter out = resp.getWriter();
        out.write(token);

    }

}
